<?php
class CV_ORM_Schema_Writer_SeparateFile{
	protected $templates;
	protected $mainTargetDirectory;
/*	protected $targetDirectories = array(
		'Model' => 'Model/',
		'ArrayAccess' => 'ArrayAccess/',
		'ObjectAccess' => 'ObjectAccess/',
		'Base_Model' => 'Base_Model/',
		'Base_ArrayAccess' => 'Base_ArrayAccess/',
		'Base_ObjectAccess' => 'Base_ObjectAccess/',
	);*/
	protected $baseDirectory;
	public function __construct( $options = array() ){
		$__DIR__ = dirname(__FILE__)."/";

		$this->templates = array(
			'Model'             => $__DIR__.'SeparateFile/Template/Model.php-tpl.php',
			'ArrayAccess'       => $__DIR__.'SeparateFile/Template/ArrayAccess.php-tpl.php',
			'ObjectAccess'      => $__DIR__.'SeparateFile/Template/ObjectAccess.php-tpl.php',
			'Model/Base'        => $__DIR__.'SeparateFile/Template/Base/Model.php-tpl.php',
			'ArrayAccess/Base'  => $__DIR__.'SeparateFile/Template/Base/ArrayAccess.php-tpl.php',
			'ObjectAccess/Base' => $__DIR__.'SeparateFile/Template/Base/ObjectAccess.php-tpl.php',
		);

		if( isset($options['targetDirectory']) ){
			$this->mainTargetDirectory = $options['targetDirectory'];
		} else {
			$this->mainTargetDirectory = dirname(dirname(dirname(dirname(dirname($__DIR__)))))."/generated/";
		}
	}
	public function write( $schema ){
		foreach( $schema->getDatabaseNames() as $database ){
			foreach( $schema->getTableNames($database) as $table ){
				$fields =  $schema->getColumnNames($database,$table);

				$vars = compact('schema','database','table','fields');

				$this->store( 'Model', false, $vars );
				$this->store( 'Model/Base', true, $vars );

				$this->store( 'ArrayAccess', false, $vars );
				$this->store( 'ArrayAccess/Base', true, $vars );

				$this->store( 'ObjectAccess', false, $vars );
				$this->store( 'ObjectAccess/Base', true, $vars );
			}
		}
	}
	protected function classToFile( $class ){
		return strtr( $class, array('_'=>DIRECTORY_SEPARATOR) ).".php";
	}
	protected function store( $id, $overwrite, $vars ){
		extract($vars);
		$class = strtr(ucwords(strtr($table,array('_'=>' '))),array(' '=>''));
		ob_start();
		require $this->templates[ $id ];
		$path = $this->mainTargetDirectory . $id . DIRECTORY_SEPARATOR . $this->classToFile($class);
		if( $overwrite || !file_exists($path) ){
			file_put_contents( $path, ob_get_clean() );
		} else {
			ob_end_clean();
		}
	}
	public function autoload( $class ){
		//foreach( $this->targetDirectories as $folder ){
			$path = $this->mainTargetDirectory . $this->classToFile($class);
			if( file_exists($path) ){
				require $path;
				return true;
			}
		//}
		return false;
	}
}